<template>
    <div class="p-4 space-y-4">
      <!-- Switch between fund and stock -->
      <div class="flex space-x-4">
        <label class="inline-flex items-center">
          <input type="radio" v-model="selectedType" value="fund" class="form-radio" />
          <span class="ml-2">Fund</span>
        </label>
        <label class="inline-flex items-center">
          <input type="radio" v-model="selectedType" value="stock" class="form-radio" />
          <span class="ml-2">Stock</span>
        </label>
      </div>
  
      <!-- ECharts line chart -->
      <div ref="chartRef" style="height: 400px;"></div>
  
      <!-- 数据输出表格 -->
      <table class="min-w-full bg-white border">
        <thead>
          <tr class="bg-gray-100">
            <th class="px-2 py-1 border">时间</th>
            <th class="px-2 py-1 border">操作</th>
            <th class="px-2 py-1 border">本金</th>
            <th class="px-2 py-1 border">当天涨跌幅 (%)</th>
            <th class="px-2 py-1 border">持仓收益</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in result" :key="row.date">
            <td class="px-2 py-1 border">{{ row.date }}</td>
            <td class="px-2 py-1 border">{{ row.operation || '-' }}</td>
            <td class="px-2 py-1 border">{{ row.principal.toFixed(2) }}</td>
            <td class="px-2 py-1 border">{{ row.riseFall.toFixed(2) }}</td>
            <td class="px-2 py-1 border">{{ row.holdingValue.toFixed(4) }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </template>
  
  <script>
  import { ref, computed, watch, onMounted } from 'vue'
  import * as echarts from 'echarts'
  
  export default {
    name: 'Backtest',
    setup() {
      // 样例买卖数据
      let buySellData = [
        { type: '买入', time: '2020-05-11', money: 20000 },
        { type: '卖出', time: '2020-05-14', money: -10000 },
        { type: '买入', time: '2020-05-18', money: 18000 },
        { type: '买入', time: '2020-05-22', money: 5000 }
      ]
  
      // 样例基金/股票价格数据
      let fundData = {
        time: [ '2020-05-07','2020-05-08',
          '2020-05-11','2020-05-12','2020-05-13','2020-05-14','2020-05-15',
          '2020-05-18','2020-05-19','2020-05-20','2020-05-21','2020-05-22'
        ],
        num: ['1461.42','1451.94',
          '1471.42','1481.94','1489.56','1460.98','1466.97',
          '1456.10','1476.50','1482.32','1449.80','1416.48'
        ],
        riseFall: [0.5,1,-0.76,0.71,0.51,-1.92,0.41,-0.74,1.4,0.39,-2.19,-2.3]
      }
      let sessionS_data=null;
      if(sessionStorage.getItem('funds_data_time')){
         sessionS_data = {
          time:JSON.parse(sessionStorage.getItem('funds_data_time')),
          funds_data:JSON.parse(sessionStorage.getItem('funds_data')),
          buySellData:JSON.parse(sessionStorage.getItem('bug_shell_all_data_array'))
        }
        // 转换为数值类型并计算每日涨跌幅
        const dailyChanges = sessionS_data.funds_data.map(Number).map((value, index, array) => {
            if (index === 0) return 0;
            return +(value - array[index - 1]).toFixed(3);
        });
        // 初始化值为1，然后累加涨跌变化
        const cumulativeValues = [1];
        dailyChanges.forEach((change, index) => {
            if (index > 0) {
                cumulativeValues.push(+(cumulativeValues[index - 1] + change / 100).toFixed(3));
            }
        });
        buySellData=sessionS_data.buySellData;
        fundData={
          time:sessionS_data.time,
          num:dailyChanges,
          riseFall:cumulativeValues,
        }
        console.log('fundData',fundData);
      }
   

      const stockData = { time: [], num: [], riseFall: [] }
  
      const selectedType = ref('fund')
      const chartRef = ref(null)
      let chartInstance = null
  
      const assetData = computed(() =>
        selectedType.value === 'fund' ? fundData : stockData
      )
  
      // 计算输出结果：时间、操作、本金、当天涨跌幅、持仓收益
      const result = computed(() => {
        const { time, num, riseFall } = assetData.value
        const rows = []
        let heldShares = 0
        let principal = 0
  
        time.forEach((date, idx) => {
          const price = parseFloat(num[idx])
          const opEntry = buySellData.find(t => t.time === date)
          const operation = opEntry ? opEntry.money : ''
  
          // 本次记录的本金（未含当天交易）
          const currentPrincipal = principal
          // 持仓收益 = 持仓份额 * 当天价格（未含当天交易）
          const holdingValue = heldShares * price
  
          rows.push({
            date,
            operation,
            principal: currentPrincipal,
            riseFall: riseFall[idx],
            holdingValue
          })
  
          // 当天交易后更新持仓份额和本金
          if (opEntry) {
            const shares = opEntry.money / price
            heldShares += shares
            principal += opEntry.money
          }
        })
  
        return rows
      })
  
      // 渲染ECharts折线图：价格 & 持仓价值
      const renderChart = () => {
        if (!chartRef.value) return
        if (!chartInstance) chartInstance = echarts.init(chartRef.value)
  
        const { time, num } = assetData.value
        const priceSeries = num.map(n => parseFloat(n))
        const holdingSeries = result.value.map(r => r.holdingValue)
  
        chartInstance.setOption({
          toolbox: { // 添加工具栏
              show: true,
              feature: {
                  dataZoom: { // 数据区域缩放
                      yAxisIndex: 'none' // 只允许X轴缩放
                  },
                  restore: {}, // 重置
                  saveAsImage: {} // 保存为图片
              }
          },
          dataZoom: [ // 添加数据缩放组件
              {
                  type: 'slider', // 滑动条缩放
                  xAxisIndex: 0,
                  filterMode: 'empty'
              },
              {
                  type: 'inside', // 鼠标滚轮缩放
                  xAxisIndex: 0,
                  zoomOnMouseWheel: true, // 鼠标滚轮缩放
                  moveOnMouseMove: true, // 鼠标拖动
                  moveOnMouseWheel: false // 鼠标滚轮不触发平移
              }
          ],
          tooltip: { trigger: 'axis' },
          legend: { data: ['累加涨跌', '持仓价值'] },
          xAxis: { type: 'category', data: time },
          yAxis: [
            { type: 'value', name: '累加涨跌' },
            { type: 'value', name: '持仓价值', position: 'right' }
          ],
          series: [
            { name: '累加涨跌', type: 'line', data: sessionS_data.funds_data },
            { name: '持仓价值', type: 'line', yAxisIndex: 1, data: holdingSeries }
          ]
        })
      }
  
      watch(assetData, renderChart)
      onMounted(renderChart)
  
      return { selectedType, chartRef, result }
    }
  }
  </script>
  
  <style scoped>
  table { border-collapse: collapse; width: 100%; }
  th, td { text-align: center; padding: 8px; }
  </style>
  